package com.course.design.service.impl;

import cn.hutool.core.io.FileUtil;
import com.course.design.common.ResultCode;
import com.course.design.dao.WjxxMapper;
import com.course.design.entity.Wjxx;
import com.course.design.exception.ExecuteException;
import com.course.design.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * 描述:
 *
 * @author qinlianji
 * @create 2020-02-27
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${design.file.root}")
    private String root;

    @Autowired
    private WjxxMapper wjxxMapper;

    @Override
    public String getRoot() {
        return this.root;
    }

    @Override
    public String buildPath(Wjxx wjxx) {
        return getRoot() + File.separator + (wjxx.getCclj() == null ? "" : (wjxx.getCclj() + File.separator)) + wjxx.getCcwjm();
    }

    @Override
    public InputStream getFileStream(Wjxx wjxx) {
        if (wjxx != null) {
            File file = new File(buildPath(wjxx));
            if (file != null && file.isFile()) {
                return FileUtil.getInputStream(file);
            } else {
                throw new ExecuteException(ResultCode.File_Unfound);
            }
        }
        throw new ExecuteException(ResultCode.File_NotExist);
    }

    @Override
    public void save(Wjxx wjxx) {
        wjxxMapper.insert(wjxx);
    }

    @Override
    public Wjxx queryById(String wjxxbsId) {
        return wjxxMapper.selectById(wjxxbsId);
    }

}
